package com.doyens.auth.controller;

import com.doyens.auth.config.JwtProperties;
import com.doyens.auth.entity.UserInfo;
import com.doyens.auth.service.AuthService;
import com.doyens.auth.utils.JwtUtils;
import com.doyens.common.utils.CookieUtils;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class AuthController {


    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AuthService authService;

    //1.前台请求过来,通过用户名和密码,调用user工程中的queryuser方法,查询用户名或者密码是否正确
    //2.如果正确,  true  生成token码保存到cookie中

    @PostMapping("accredit")
    public ResponseEntity<Void>  accredit(@RequestParam("username") String username,
                                          @RequestParam("password") String password,
                                          HttpServletRequest request,
                                          HttpServletResponse response){
       String token =   authService.accredit(username,password);
       if (StringUtils.isBlank(token)){
           return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
       }

       //把token码设置到cookie中
        CookieUtils.setCookie(request,response,this.jwtProperties.getCookieName(),token,this.jwtProperties.getExpire() * 60);
        return ResponseEntity.ok(null);

    }

    //展示首页登录用户
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("DY_TOKEN") String token,HttpServletRequest request,HttpServletResponse response){
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
            if (userInfo == null){
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            //刷新token中的有效时间
            token = JwtUtils.generateToken(userInfo, this.jwtProperties.getPrivateKey(), this.jwtProperties.getExpire());

            //刷新cookie中的有效时间
            CookieUtils.setCookie(request,response,this.jwtProperties.getCookieName(),token,this.jwtProperties.getExpire()*60);


            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }


}
